package org.linlinjava.litemall.admin.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.linlinjava.litemall.db.dao.LitemallCarModelMapper;
import org.linlinjava.litemall.db.domain.LitemallCarBrand;
import org.linlinjava.litemall.db.domain.LitemallCarModel;
import org.linlinjava.litemall.db.service.LitemallCarModelService;
import org.linlinjava.litemall.db.service.LitemallCarSeriesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class AdminCarModelService {

    @Autowired
    LitemallCarModelService litemallCarModelService;

    private final Log logger = LogFactory.getLog(AdminCarModelService.class);

    public void httpRequest(int seriesid,int newId){
        //根据句上一级的seriesId确定接口查询的api
        String apiPath = "https://www.autohome.com.cn/ashx/index/GetHomeFindCar.ashx?type=2&seriesid="+seriesid+"&format=json";
        //同样使用httpclient和httpget对接口进行请求并接受返回的数据
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet post = new HttpGet(apiPath);
        try{
            post.addHeader("content-type","text/xml");
            HttpResponse res = client.execute(post);
            //根据状态码,判断请求返回是否成功
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                String result = EntityUtils.toString(res.getEntity());
                if (result.length() >= 2){//因为有的车型没有具体款式,所以加一个判断

                    //使用jsonArray对json串解析
                    JSONArray jsonArray = JSONArray.parseArray(result);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        //将json数组的每一个对象解析为jsonObject
                        JSONObject object = jsonArray.getJSONObject(i);
                        String onSell = object.getString("name");
                        String detail = object.getString("list");
                        //继续嵌套解析,根据json字符串格式解析为jsonArray数组
                        JSONArray array = JSONArray.parseArray(detail);
                        for (int j = 0; j < array.size(); j++) {
                            JSONObject model = array.getJSONObject(j);

                            if (model.getString("name").length() >= 5){
                                //将实体对象实例化
                                LitemallCarModel carModel = new LitemallCarModel();
                                //将汽车之家中以元为单位的价格换成以万为单位
                                int price = model.getInteger("price");
                                double num = Math.round(price * 1000) * 0.0001* 0.001d ;
                                carModel.setPrice(BigDecimal.valueOf(num));

                                carModel.setName(model.getString("name"));
                                int newModelId = model.getInteger("id");


                                int flag = 0;//加入一个判断,对数据插入还是更新做出判断,flag为0代表是插入,flag为1代表更新
                                while (litemallCarModelService.findById(newModelId) != null){
                                    //获取数据库中和id对应的一条数据
                                    LitemallCarModel car = litemallCarModelService.findById(newModelId);
                                    //判断id和name是否完全一致,相同说明是同一条数据,要进行更新,不同则id++接着进行下一次的判断.
                                    if (car.getId() == newModelId && car.getName().equals(model.getString("name"))){
                                        flag = 1;
                                        break;
                                    }
                                    newModelId++;
                                }

                                //将json对象的数据写入实体化对象中
                                carModel.setId(newModelId);
                                String group = model.getString("name").substring(0,5);
                                carModel.setGroup(group);
                                carModel.setSeriesId(newId);
                                carModel.setSellstate(onSell);
                                carModel.setDeleted(String.valueOf(0));

                                if (flag == 1){//数据更新
                                    litemallCarModelService.updateById(carModel);
                                }else {//数据插入
                                    litemallCarModelService.add(carModel);
                                }

                            }


                        }
                    }



                }

            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            throw new RuntimeException(e);
        }

    }

}
